package org.jeecg.modules.exProject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exProject.entity.ExProjectAttachments;
import org.jeecg.modules.exProject.mapper.ExProjectAttachmentsMapper;
import org.jeecg.modules.exProject.service.IExProjectAttachmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;

 /**
 * @Description: 项目附件
 * @Author: jeecg-boot
 * @Date:   2024-12-21
 * @Version: V1.0
 */
@Api(tags="项目附件")
@RestController
@RequestMapping("/exProject/exProjectAttachments")
@Slf4j
public class ExProjectAttachmentsController extends JeecgController<ExProjectAttachments, IExProjectAttachmentsService> {
	@Autowired
	private IExProjectAttachmentsService exProjectAttachmentsService;
	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;

	 /**
	  * 本地：local minio：minio 阿里：alioss
	  */
	 @Value(value="${jeecg.uploadType}")
	 private String uploadType;
	 @Autowired
	 private ExProjectAttachmentsMapper exProjectAttachmentsMapper;
	
	/**
	 * 分页列表查询
	 *
	 * @param exProjectAttachments
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "项目附件-分页列表查询")
	@ApiOperation(value="项目附件-分页列表查询", notes="项目附件-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ExProjectAttachments>> queryPageList(ExProjectAttachments exProjectAttachments,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ExProjectAttachments> queryWrapper = QueryGenerator.initQueryWrapper(exProjectAttachments, req.getParameterMap());
		Page<ExProjectAttachments> page = new Page<ExProjectAttachments>(pageNo, pageSize);
		IPage<ExProjectAttachments> pageList = exProjectAttachmentsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param exProjectAttachments
	 * @return
	 */
	@AutoLog(value = "项目附件-添加")
	@ApiOperation(value="项目附件-添加", notes="项目附件-添加")
	//@RequiresPermissions("org.jeecg.modules:ex_project_attachments:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ExProjectAttachments exProjectAttachments) {
		exProjectAttachmentsService.save(exProjectAttachments);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param exProjectAttachments
	 * @return
	 */
	@AutoLog(value = "项目附件-编辑")
	@ApiOperation(value="项目附件-编辑", notes="项目附件-编辑")
	//@RequiresPermissions("org.jeecg.modules:ex_project_attachments:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ExProjectAttachments exProjectAttachments) {
		exProjectAttachmentsService.updateById(exProjectAttachments);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目附件-通过id删除")
	@ApiOperation(value="项目附件-通过id删除", notes="项目附件-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:ex_project_attachments:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		exProjectAttachmentsService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目附件-批量删除")
	@ApiOperation(value="项目附件-批量删除", notes="项目附件-批量删除")
	//@RequiresPermissions("org.jeecg.modules:ex_project_attachments:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.exProjectAttachmentsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目附件-通过id查询")
	@ApiOperation(value="项目附件-通过id查询", notes="项目附件-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ExProjectAttachments> queryById(@RequestParam(name="id",required=true) String id) {
		ExProjectAttachments exProjectAttachments = exProjectAttachmentsService.getById(id);
		if(exProjectAttachments==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(exProjectAttachments);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param exProjectAttachments
    */
    //@RequiresPermissions("org.jeecg.modules:ex_project_attachments:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExProjectAttachments exProjectAttachments) {
        return super.exportXls(request, exProjectAttachments, ExProjectAttachments.class, "项目附件");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("ex_project_attachments:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ExProjectAttachments.class);
    }


	 /**
	  * @Author 政辉
	  * @return
	  */
	 @GetMapping("/403")
	 public Result<?> noauth()  {
		 return Result.error("没有权限，请联系管理员授权");
	 }

	 /**
	  * 文件上传统一方法
	  * @param request
	  * @param response
	  * @return
	  */
	 @ApiOperation(value="项目附件-文件上传统一方法", notes="项目附件-通过id查询")
	 @PostMapping(value = "/upload")
	 public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
		 Result<?> result = new Result<>();
		 String savePath = "";
		 String bizPath = request.getParameter("biz");

		 //LOWCOD-2580 sys/common/upload接口存在任意文件上传漏洞
		 if (oConvertUtils.isNotEmpty(bizPath)) {
			 if(bizPath.contains(SymbolConstant.SPOT_SINGLE_SLASH) || bizPath.contains(SymbolConstant.SPOT_DOUBLE_BACKSLASH)){
				 throw new JeecgBootException("上传目录bizPath，格式非法！");
			 }
		 }

		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 // 获取上传文件对象
		 MultipartFile file = multipartRequest.getFile("file");
		 if(oConvertUtils.isEmpty(bizPath)){
			 if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
				 //未指定目录，则用阿里云默认目录 upload
				 bizPath = "upload";
				 //result.setMessage("使用阿里云文件上传时，必须添加目录！");
				 //result.setSuccess(false);
				 //return result;
			 }else{
				 bizPath = "";
			 }
		 }
		 if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
			 //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
			 savePath = this.uploadLocal(file,bizPath);
			 //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
			 /**  富文本编辑器及markdown本地上传时，采用返回链接方式
			  //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
			  String jeditor = request.getParameter("jeditor");
			  if(oConvertUtils.isNotEmpty(jeditor)){
			  result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
			  result.setSuccess(true);
			  return result;
			  }else{
			  savePath = this.uploadLocal(file,bizPath);
			  }
			  */
		 }else{
			 //update-begin-author:taoyan date:20200814 for:文件上传改造
			 savePath = CommonUtils.upload(file, bizPath, uploadType);
			 //update-end-author:taoyan date:20200814 for:文件上传改造
		 }
		 if(oConvertUtils.isNotEmpty(savePath)){
			 result.setMessage(savePath);
			 result.setSuccess(true);
		 }else {
			 result.setMessage("上传失败！");
			 result.setSuccess(false);
		 }
		 saveAttachmentRecord(file, savePath);
		 return result;
	 }

	 /**
	  * 本地文件上传
	  * @param mf 文件
	  * @param bizPath  自定义路径
	  * @return
	  */
	 private String uploadLocal(MultipartFile mf,String bizPath){
		 try {
			 String ctxPath = uploadpath;
			 String fileName = null;
			 File file = new File(ctxPath + File.separator + bizPath + File.separator );
			 if (!file.exists()) {
				 // 创建文件根目录
				 file.mkdirs();
			 }
			 // 获取文件名
			 String orgName = mf.getOriginalFilename();
			 orgName = CommonUtils.getFileName(orgName);
			 if(orgName.indexOf(SymbolConstant.SPOT)!=-1){
				 fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
			 }else{
				 fileName = orgName+ "_" + System.currentTimeMillis();
			 }
			 String savePath = file.getPath() + File.separator + fileName;
			 File savefile = new File(savePath);
			 FileCopyUtils.copy(mf.getBytes(), savefile);
			 String dbpath = null;
			 if(oConvertUtils.isNotEmpty(bizPath)){
				 dbpath = bizPath + File.separator + fileName;
			 }else{
				 dbpath = fileName;
			 }
			 if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) {
				 dbpath = dbpath.replace(SymbolConstant.DOUBLE_BACKSLASH, SymbolConstant.SINGLE_SLASH);
			 }
			 saveAttachmentRecord(mf, dbpath);
			 return dbpath;
		 } catch (IOException e) {
			 log.error(e.getMessage(), e);
		 }
		 return "";
	 }

	 private void saveAttachmentRecord(MultipartFile file, String filePath) {
		 String fileName = file.getOriginalFilename();
		 fileName = CommonUtils.getFileName(fileName);
		 ExProjectAttachments attachments = new ExProjectAttachments();
		 attachments.setAttachmentCount(BigDecimal.ZERO);
		 attachments.setAttachmentName(fileName);
		 attachments.setAttachmentFileName(fileName);
		 attachments.setAttachmentCode(fileName);
		 attachments.setAttachmentType(fileName.substring(fileName.lastIndexOf(".") + 1));
		 attachments.setUrl(filePath);
		 exProjectAttachmentsService.getBaseMapper().insert(attachments);
	 }

}
